package com.wt.admin.service.impl;


import com.wt.admin.entity.SmsCode;
import com.wt.admin.service.SmsCodeService;
import com.wt.admin.service.SmsService;
import com.wt.encryptionPass.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SmsCodeServiceImpl implements SmsCodeService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SmsService smsService;

    @Override
    public boolean sentSms(String phone) {
        // 发送短信验证码
        // 判断redis中是否存在验证码
        String sms = (String) redisTemplate.opsForValue().get(phone);
        if (sms == null) {
            // redis不存在，生成验证码发送
            String code = RandomUtil.getFourBitRandom();
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            Map<String,Object> param = new HashMap<>();
            param.put("code",code);
            boolean isSent = smsService.sent(phone, param);
            if (isSent) {
                return true;// 发送成功
            }
        }else {
            // redis存在直接发送
            Map<String,Object> param = new HashMap<>();
            param.put("code",sms);
            boolean isSent = smsService.sent(phone, param);
            if (isSent) {
                return true;// 发送成功
            }
        }
        return false;
    }

    @Override
    public boolean checkSms(SmsCode smsCode) {
        // 1、缓存redis中取出验证码进行匹配
        String sms = (String) redisTemplate.opsForValue().get(smsCode.getPhone());
        if (smsCode.getSms().equals(sms)) return true;
        return false;
    }
}
